<template>
  <div class="userBox bg-f2">
    <div class="bg-fff">
      <el-breadcrumb separator-class="el-icon-arrow-right" class="pAll">
        <el-breadcrumb-item>
          <span @click="goBack" class="goTitle">设备电压电流</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ titles[titleCount] }}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form :model="ruleForm" class="pAll" :rules="rules" ref="ruleForm" label-width="130px">
        <el-row>
          <el-col :span="2">
            <span class="title">电压电流信息：</span>
          </el-col>
          <el-col :span="18" :offset="1">
            <el-form-item label="品牌：" prop="brand">
              <el-select v-model="ruleForm.brand" clearable placeholder="请选择" class="inputSelect">
                <el-option v-for="item in brandList" :no-data-text="brandTip" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="型号:" prop="model">
              <el-input placeholder="型号" class="w360" v-model.trim="ruleForm.model"></el-input>
            </el-form-item>
            <el-form-item label="类型：" prop="types">
              <!-- 直流- 1  交流-2 -->
              <!-- <el-radio v-model="ruleForm.types" label="1">直流</el-radio>
              <el-radio v-model="ruleForm.types" label="2">交流</el-radio> -->
              <el-radio-group v-model="ruleForm.types">
                <el-radio label="1">直流</el-radio>
                <el-radio label="2">交流</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="设备电压:" prop="min_voltage" class="mb_8">
              <el-input placeholder="请输入内容" class="w150 append_bg" v-model.number="ruleForm.min_voltage" @input="handleInput($event, 'min_voltage')" @blur="blurInput($event, 'min_voltage')">
                <template slot="append">V</template>
              </el-input>
              <span style="padding: 0 10px">-</span>
              <el-form-item label="" prop="max_voltage" :rules="rules.max_voltage" class="inline">
                <el-input placeholder="请输入内容" class="w150 append_bg" v-model.number="ruleForm.max_voltage" @input="handleInput($event, 'max_voltage')" @blur="blurInput($event, 'max_voltage')">
                  <template slot="append">V</template>
                </el-input>
              </el-form-item>
            </el-form-item>
            <el-form-item>
              <span style="color: #909399; padding-top: 8px">输入最低限制电流和最高限制电流</span>
            </el-form-item>
            <el-form-item label="设备电流:" prop="min_current" class="mb_8">
              <el-input placeholder="请输入内容" class="w150 append_bg" v-model.number="ruleForm.min_current" @input="handleInput($event, 'min_current')">
                <template slot="append">mA</template>
              </el-input>
              <span style="padding: 0 10px">-</span>
              <el-form-item label="" prop="max_current" :rules="rules.max_current" class="inline">
                <el-input placeholder="请输入内容" class="w150 append_bg" v-model.number="ruleForm.max_current" @input="handleInput($event, 'max_current')">
                  <template slot="append">mA</template>
                </el-input>
              </el-form-item>
            </el-form-item>
            <el-form-item>
              <span style="color: #909399; padding-top: 8px">输入最低限制电压和最高限制电压</span>
            </el-form-item>
            <!-- <el-form-item label="图片:" prop="imgUrl" ref="uploadElement">
              <el-upload
                action="#"
                ref="uploadxls"
                accept=".jpg,.jpeg,.png"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="lalal"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt />
              </el-dialog>
              <span class="el-upload__tip">只能上传jpg/png文件，且不超过2M</span>
            </el-form-item> -->
            <el-form-item label="备注：">
              <el-input class="w_600" v-model.trim="ruleForm.remarks" clearable type="textarea" :rows="6" :maxlength="100" resize="none" show-word-limit placeholder="请填写备注内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="fooer_btn">
          <el-button size="medium" class="btnSizeStyle" @click="goBack">取 消</el-button>
          <el-button type="primary" class="btnSizeStyle" :loading="loadingBtn" v-if="titleCount === 1" size="medium" @click="xgBtn()" v-preventReClick>修 改</el-button>
          <el-button type="primary" class="btnSizeStyle" :loading="loadingBtn" v-else size="medium" @click="submitBtn()" v-preventReClick>保 存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getUrl, setUrl } from '@/utils/getUrl.js'
import { ziC, upload, dydl } from '@/utils/allUrl.js'
export default {
  data() {
    // 图片验证
    // var validateNum = (rule, array, callback) => {
    //   // console.log(this.imgUrl)
    //   console.log(rule, array)
    //   if (this.imgUrl.length < 0) {
    //     callback(new Error('请添加图片'))
    //   }
    // if (value < 0 || value > 255) {
    // } else {
    //   callback()
    // }
    // }
    var validateNum_dl = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('最小数值为0'))
      } else if (value > 30000) {
        callback(new Error('最大数值不超过3000'))
      } else {
        callback()
      }
    }
    var validateNum_dy = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('最小数值为0'))
      } else if (value > 280) {
        callback(new Error('最大数值不超过280'))
      } else {
        callback()
      }
    }
    return {
      titles: ['录入电压电流', '编辑电压电流'],
      titleCount: '',
      brandList: [], // 品牌
      ruleForm: {
        id: '',
        brand: '', // 品牌
        model: '', // 型号
        types: 0, // 类型
        max_voltage: '0.00', // 最大电压
        min_voltage: '0.00', // 最小电压
        max_current: 0, // 最大电流
        min_current: 0, // 最小电流
        remarks: '', // 备注
      },
      brandTip: '',
      rules: {
        brand: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        model: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
        types: [{ required: true, message: '请选择类型', trigger: 'change' }],
        min_current: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          { validator: validateNum_dl, trigger: 'blur' },
        ],
        max_current: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          { validator: validateNum_dl, trigger: 'blur' },
        ],
        min_voltage: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          { validator: validateNum_dy, trigger: 'blur' },
        ],
        max_voltage: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          { validator: validateNum_dy, trigger: 'blur' },
        ],
        // imgUrl: [{ required: true, message: '请上传图片', trigger: 'blur' }],
      },
      loadingBtn: false, // 防重复点击
      imgUrl: [], //  图片上传
      fileList: [], // 上传图片列表
      dialogVisible: false,
      dialogImageUrl: '', // 预览
    }
  },
  created: function () {
    const { title } = this.$route.query
    this.titleCount = title
    // 编辑电流电压
    if (Number(title) === 1) {
      const list = JSON.parse(getUrl('voltageCurrentList'))
      list.types = list.types.toString()
      list.max_voltage = Number(list.max_voltage)
      // const cao = list.image.replace(/uid/g, 'name')

      // this.fileList = JSON.parse(cao)
      // this.imgUrl = this.fileList
      list.image.split(',').forEach((item, index) => {
        this.fileList.push({
          uid: index,
          url: item,
        })
      })
      // console.log(list.image.split(','))
      // this.fileList = list.image.split(',')
      this.ruleForm = list
    }
    // 录入电流电压
    if (Number(title) === 0) {
      this.ruleForm.types = '1'
    }
    this.initBrand() // 获取品牌
  },
  mounted() {},
  methods: {
    // 图片
    async savePicture(imgList) {
      const params = new URLSearchParams()
      params.append('image', imgList.join(','))
      const { data: res } = await this.$http.post(`${ziC}standard/savePicture`, params)
      console.log(res)
    },
    // 添加图片
    async lalal(el) {
      const file = el.raw
      const fd = new FormData()
      let arr = {}
      fd.append('file', file) // 传文件
      fd.append('type', 0) // 传文件
      const { data: res } = await this.$http.post(`${upload}`, fd)
      res.data.forEach((item) => {
        arr = {
          uid: el.uid,
          url: item,
        }
        this.imgUrl.push(arr)
      })
      console.log(this.imgUrl)
    },
    // 预览
    handlePictureCardPreview(e) {
      this.dialogImageUrl = e.url
      this.dialogVisible = true
    },
    // 删除图片
    handleRemove(a) {
      const index = this.imgUrl.findIndex((item) => item.uid === a.uid)
      this.imgUrl.splice(index, 1)
    },
    handleInput(value, id) {
      if (id === 'min_voltage' || id === 'max_voltage') {
        value = value.replace(/[^0-9.]/g, '') // 限制只输入数字和.
        if (value.indexOf('.') > 0) {
          value = value.slice(0, value.indexOf('.') + 3) // 限制小数点位数
        }
      } else {
        value = value.replace(/[^0-9]/g, '') // 限制只输入数字和.
      }
      this.ruleForm[`${id}`] = value
    },
    blurInput(e, id) {
      const value = e.target.value
      const fistValue = Number(value.toString().split('.')[0])
      let lastValue = ''
      if (value.toString().split('.').length > 1) {
        lastValue = value.toString().split('.')[1]
        if (lastValue.length > 2) {
          lastValue = `.${value.toString().split('.')[1].slice(0, 2)}`
        }
        if (lastValue.length === 1) {
          lastValue = `.${value.toString().split('.')[1]}0`
        }
        if (lastValue.length === 2) {
          lastValue = `.${value.toString().split('.')[1]}`
        }
        if (value.toString().split('.')[1] === '') {
          lastValue = '.00'
        }
      } else {
        lastValue = '.00'
      }
      this.ruleForm[`${id}`] = `${fistValue}${lastValue}`
    },
    // 获取品牌
    async initBrand() {
      var arr = []
      const { data: res } = await this.$http.post(`${ziC}pp/list`)
      switch (res.code) {
        case '0000':
          res.data.list.forEach((item) => {
            const k = {
              value: item.id,
              label: item.ppmc,
            }
            arr.push(k)
          })
          this.brandList = arr
          break
        default:
          this.brandList = []
          this.brandTip = res.message
          break
      }
    },
    async xgBtn() {
      const list = JSON.parse(JSON.stringify(this.ruleForm))
      const images = []
      if (this.ruleForm.min_current > this.ruleForm.max_current) {
        this.ruleForm.min_current = list.max_current
        this.ruleForm.max_current = list.min_current
      }
      if (this.ruleForm.min_voltage > this.ruleForm.max_voltage) {
        this.ruleForm.min_voltage = list.max_voltage
        this.ruleForm.max_voltage = list.min_voltage
      }
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { id, model, brand, types, max_voltage, min_voltage, max_current, min_current, remarks } = this.ruleForm
        const params = new URLSearchParams()
        params.append('id', id)
        params.append('model', model)
        params.append('brand', brand)
        params.append('types', types)
        params.append('max_voltage', max_voltage)
        params.append('min_voltage', min_voltage)
        params.append('max_current', max_current)
        params.append('min_current', min_current)
        params.append('remarks', remarks)
        this.imgUrl.forEach((item) => {
          images.push(item.url)
        })
        params.append('image', images.join(','))
        const { data: res } = await this.$http.post(`${dydl}standard/updates`, params)
        switch (res.code) {
          case '0000':
            this.savePicture(images)
            this.$message.success(res.message)
            this.goBack()
            break
          case '0016':
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 覆盖
                this.coverStandard()
              })
              .catch(() => {})
            break
          default:
            this.$message.error(res.message)
            break
        }
      })
    },
    cleanValidate(formName) {
      // 清除表单校验的提示
      if (this.$refs[formName]) {
        // 延时执行
        this.$nextTick(function () {
          this.$refs[formName].clearValidate()
        })
      }
    },
    // 保存
    submitBtn() {
      // this.rules.imgUrl = [{ required: true, message: '请上传图片' }]
      // if (this.imgUrl.length > 0) {
      //   console.log(this.imgUrl.length, this.$refs.uploadElement)
      //   this.$nextTick(function () {
      //     this.cleanValidate('uploadElement')
      //   })
      // }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          return
        }
        // 图片验证
        // if (this.imgUrl.length < 1) {
        //   this.$message.error('请添加图片')
        //   return
        // }
        const list = JSON.parse(JSON.stringify(this.ruleForm))
        if (this.ruleForm.min_current > this.ruleForm.max_current) {
          console.log(this.ruleForm)
          this.ruleForm.min_current = list.max_current
          this.ruleForm.max_current = list.min_current
        }
        if (this.ruleForm.min_voltage > this.ruleForm.max_voltage) {
          this.ruleForm.min_voltage = list.max_voltage
          this.ruleForm.max_voltage = list.min_voltage
        }
        this.loadingBtn = true
        this.changeList()
      })
    },
    async changeList() {
      const imgList = []
      this.imgUrl.forEach((item) => {
        imgList.push(item.url)
      })
      const { title } = this.$route.query
      const { id, model, brand, types, max_voltage, min_voltage, max_current, min_current, remarks } = this.ruleForm
      const params = new URLSearchParams()
      if (Number(title) === 1) {
        // 修改
        params.append('id', id)
      }
      params.append('model', model)
      params.append('brand', brand)
      params.append('types', types)
      params.append('max_voltage', max_voltage)
      params.append('min_voltage', min_voltage)
      params.append('max_current', max_current)
      params.append('min_current', min_current)
      params.append('remarks', remarks)
      // params.append('image', imgList.join(','))
      const { data: res } = await this.$http.post(`${dydl}standard/inserts`, params)
      this.loadingBtn = false
      switch (res.code) {
        case '0000':
          this.savePicture(imgList)
          this.$message.success(res.message)
          this.goBack()
          break
        case '0016':
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              // 覆盖
              this.coverStandard()
            })
            .catch(() => {})
          break
        default:
          this.$message.error(res.message)
          break
      }
    },
    // 覆盖
    async coverStandard() {
      // this.$refs.ruleForm.validate(async (valid) => {
      //   if (!valid) {
      //     return
      //   }
      const imgList = []
      this.imgUrl.forEach((item) => {
        imgList.push(item.url)
      })
      const { id, model, brand, types, max_voltage, min_voltage, max_current, min_current, remarks } = this.ruleForm
      const params = new URLSearchParams()
      params.append('id', id)
      params.append('model', model)
      params.append('brand', brand)
      params.append('types', types)
      params.append('max_voltage', max_voltage)
      params.append('min_voltage', min_voltage)
      params.append('max_current', max_current)
      params.append('min_current', min_current)
      params.append('image', imgList.join(','))
      params.append('remarks', remarks)
      const { data: res } = await this.$http.post(`${dydl}standard/coverStandard`, params)
      switch (res.code) {
        case '0000':
          this.savePicture(imgList)
          this.$message.success(res.message)
          this.goBack()
          break
        default:
          this.$message.error(res.message)
          break
      }
      // })
    },

    // 返回列表界面
    goBack: function () {
      setUrl('parameter', 'voltageCurrent')
      this.$router.push('/voltageCurrent')
    },
  },
}
</script>
<style lang="scss" scoped>
.w150 {
  width: 150px;
}
.w_600 {
  width: 600px;
}
.mb_8 {
  margin-bottom: 8px;
}
.inline {
  display: inline-block;
}
.fooer_btn {
  margin: 10px 0;
  display: flex;
  justify-content: flex-end;
}
.w360 {
  width: 360px;
}
::v-deep .append_bg .el-input-group__append {
  background-color: #f5f7fa;
}
</style>
